<template>
  <button
    ref="buttonRef"
    class="popmotion-button"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
  >
    <slot></slot>
  </button>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { animate } from "popmotion"

const buttonRef = ref<HTMLButtonElement | null>(null)

let animation: { stop: () => void; } | undefined

const handleMouseEnter = () => {
  if (!buttonRef.value) return
  const button = buttonRef.value
  animation = animate({
    from: {
      scale: 1,
      y: 0,
    },
    to: {
      scale: 1.1,
      y: -5,
    },
    type: 'spring',
    stiffness: 300,
    damping: 10,
    onUpdate: (latest) => {
      if (button) {
        button.style.transform = `scale(${latest.scale}) translateY(${latest.y}px)`
      }
    }
  })
}

const handleMouseLeave = () => {
  if (!buttonRef.value) return
  if (animation) {
    animation.stop()
  }
  const button = buttonRef.value
  animate({
    from: {
      scale: 1.1,
      y: -5,
    },
    to: {
      scale: 1,
      y: 0,
    },
    type: 'spring',
    stiffness: 300,
    damping: 10,
    onUpdate: (latest) => {
      if (button) {
        button.style.transform = `scale(${latest.scale}) translateY(${latest.y}px)`
      }
    }
  })
}

onUnmounted(() => {
  if (animation) {
    animation.stop()
  }
})
</script>

<style scoped>
.popmotion-button {
  border-radius: 25px;
  padding: 8px 20px;
  height: auto;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(59, 130, 246, 0.2);
  color: #475569;
  backdrop-filter: blur(15px);
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: none;
  outline: none;
}

.popmotion-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.1), transparent);
  transition: left 0.5s;
}

.popmotion-button:hover::before {
  left: 100%;
}

.popmotion-button:hover {
  background: rgba(255, 255, 255, 0.9);
  border-color: rgba(59, 130, 246, 0.4);
  color: #3b82f6;
  box-shadow: 0 10px 30px rgba(59, 130, 246, 0.25);
}
</style>